<?php
namespace App\Service\ApiQd;

use Illuminate\Support\Facades\DB;

class GoodsService extends BaseService
{
    //商品

    /**
     * 分类列表
     * @return array
     */
    public function getCateList()
    {
        $db = $this->dbwbConn($this->dbDistributorGcate)
            ->where('del', 0)
            ->where('pid', 0);
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => 0);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $imglink = $v['img'] ? env('DOMAIN') . '/' . $v['img'] : '';
            $arys[] = [
                'id' => $v['id'],
                'img' => $imglink,
                'title' => $v['title'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 商品列表
     * @param array $pages【start，limit】
     * @param int $cateid 分类ID
     * @param array $pas【is_sale，is_price，is_new】
     * @param int $uid
     * @return array
     */
    public function getGoodsList($pages, $cateid, $keyword, $pas = [], $user = [])
    {
        $uid = $user['id'];
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbwbConn($this->dbDistributorGoods)->where('del', 0)->where('is_shelf', 1);
        if ($cateid) {
            $cateAry = [$cateid];
            $cateOnes = $this->dbwbConn($this->dbQdGcate)
                ->where('del', 0)
                ->where('pid', $cateid)
                ->get();
            if (count($cateOnes)) {
                foreach ($cateOnes as $v) {
                    $v = (array) $v;
                    $cateAry[] = $v['id'];
                }
            }
            $db = $db->whereIn('cate_id', $cateAry);
        }
        if ($keyword) {
            $db = $db->where('title', 'like', '%'.$keyword.'%');
        }
        if (isset($pas['is_new']) && $pas['is_new']) {
            $db = $db->where('isnew',1);
        }
        if (isset($pas['is_in_reason']) && $pas['is_in_reason']) {
            $db = $db->where('is_in_reason',1);
        }
        $total = $db->count();
        $db = $db->skip($start)->take($pages['limit']);
        if (isset($pas['is_sale']) && $pas['is_sale']) {
            $isSale = $pas['is_sale']==1 ? 'desc' : 'asc';
            $db = $db->orderBy('sale', $isSale);
        }
        if (isset($pas['is_price']) && $pas['is_price']) {
            $isPrice = $pas['is_price']==1 ? 'desc' : 'asc';
            if($user['level'] == 1){
                $db = $db->orderBy('price_one', $isPrice);
            }elseif ($user['level'] == 2){
                $db = $db->orderBy('price_two', $isPrice);
            } else{
                $db = $db->orderBy('price', $isPrice);
            }
        }
        $res = $db->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => $total);
        }
        $arys = [];
        $price_column = $user['level'] == 1 ? 'price_one' : 'price_two';
        foreach ($res as $v) {
            $v = (array) $v;
            //分类
            $cateOne = (array) $this->dbwbConn($this->dbDistributorGcate)->where('id', $v['id'])->first();
            //价格
            $skuid = 0; $price = $price_level = $price_one = $price_two = 0;
            $skuOne = (array) $this->dbwbConn($this->dbDistributorGsku)->where('del', 0)
                ->where('gid', $v['id'])
                ->orderBy('price', 'asc')
                ->orderBy('price_one', 'asc')
                ->orderBy('price_two', 'asc')
                ->first();
            if (!empty($skuOne)) {
                $skuid = $skuOne['id'];
                $price = $skuOne['price'];
                $price_one = $skuOne['price_one'];
                $price_two = $skuOne['price_two'];
                $price_level = $skuOne[$price_column];
            }
            $arys[] = [
                'id' => $v['id'],
                'gno' => $v['gno'],
                'title' => $v['title'],
                'cate_id' => $v['cate_id'],
                'cateName' => $cateOne ? $cateOne['title'] : '',
                'img' => env('DOMAIN'). '/' . $v['bigimg'],
                'sku_id' => $skuid,
                'price' => toNumber($price),
                'price_level' => toNumber($price_level),
                'price_one' => toNumber($price_one),
                'price_two' =>  toNumber($price_two),
                'sale' => $v['sale'],
                'isnew' => $v['isnew'],
                'cartNum' => $this->getCartTotal($uid, $v['id']),
                'part' => 'chengfen',
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    //购物车数量
    public function getCartTotal($uid, $gid)
    {
        if (!$uid) {
            return 0;
        }
        return $this->dbwbConn($this->dbDistributorCart)->where('del', 0)
            ->where('uid', $uid)
            ->where('gid', $gid)
            ->where('isorder', 0)
            ->sum('num');
    }

    //商品选项
    public function getOption()
    {
        $arys = [];
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    //商品详情
    public function getGoodsOne($gid, $user = [])
    {
        $arys['gid'] = $gid;
        $arys['gprice'] = 0;
        $arys['gprice_level'] = 0;
        $arys['gprice_one'] = 0;
        $arys['gprice_two'] = 0;
        $arys['gsale'] = 0;
        $price_column = $user['level'] == 1 ? 'price_one' : 'price_two';
        //商品详情
        $gOne = (array) $this->dbwbConn($this->dbDistributorGoods)->where('id', $gid)->first();
        if (!empty($gOne)) {
            $arys['gname'] = $gOne['title'];
            $arys['gsale'] = $gOne['sale'];
            $arys['gdetail'] = $gOne['detail'] ? htmlspecialchars_decode($gOne['detail']) : '';
        }
        //商品图片
        $gImgs = $this->dbwbConn($this->dbDistributorGimg)->where('del', 0)->where('gid', $gid)->get();
        if (count($gImgs)) {
            foreach ($gImgs as $v) {
                $v = (array) $v;
                $arys['gimgs'][] = env('DOMAIN') . '/' . $v['link'];
            }
        }
        //SKU
        $skuOnes = $this->dbwbConn($this->dbDistributorGsku)->where('del', 0)
            ->where('gid', $gid)
            ->orderBy('price', 'asc')
            ->orderBy('price_one', 'asc')
            ->orderBy('price_two', 'asc')
            ->get();
        if (count($skuOnes)) {
            foreach ($skuOnes as $v) {
                $v = (array) $v;
                $arys['skuList'][] = [
                    'sku_id' => $v['id'],
                    'sku_name' => $v['title'],
                    'price' => toNumber($v['price']),
                    'price_level' => toNumber($v[$price_column]),
                    'price_one' => toNumber($v['price_one']),
                    'price_two' => toNumber($v['price_two']),
                ];
            }
            $v0 = (array) $skuOnes[0];
            $arys['gprice'] = toNumber($v0['price']);
            $arys['gprice_level'] = toNumber($v0[$price_column]);
            $arys['gprice_one'] = toNumber($v0['price_one']);
            $arys['gprice_two'] = toNumber($v0['price_two']);
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    //关键词获取
    public function getKeywordList($uid)
    {
        $db = $this->dbwbConn($this->dbDistributorGkeyword)
            //->distinct('word')
            ->where('del', 0)
            ->where('uid', $uid)
            ->groupBy('word');
        $total = $db->count();
        $res = $db->skip(0)->take(4)->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有搜索词', 'data' => [], 'total' => 0);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $total = $this->dbwbConn($this->dbDistributorGkeyword)
                ->where('del', 0)
                ->where('uid', $uid)
                ->where('word', $v['word'])
                ->count();
            if ($v) {
                $arys[] = [
                    'id' => $v['id'],
                    'title' => $v['word'],
                    'total' => $total,
                ];
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' =>$total);
    }

    /**
     * 关键词记录
     * @param int $uid
     */
    public function addKeyword($word, $uid)
    {
        return $this->dbwbConn($this->dbDistributorGkeyword)->insertGetId([
            'uid' => $uid,
            'word' => $word,
            'addtime' => toDate(),
        ]);
    }

    /**
     * 关键词清理
     * @param int $uid
     **/
    public function keywordBatchDel($uid)
    {
        return $this->dbwbConn($this->dbDistributorGkeyword)
            ->where('uid', $uid)
            ->update([
                'del' => 1,
                'deltime' => toDate(),
            ]);
    }

    /**
     * SKU列表
     * @param array $pages【start，limit】
     * @param int $gid
     * @return array
     */
    public function getSkuList($pages, $gid, $user = [])
    {
        $price_column = $user['level'] == 1 ? 'price_one' : 'price_two';
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbwbConn($this->dbDistributorGsku)->where('del', 0)->where('gid', $gid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => $total);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'sku_id' => $v['id'],
                'title' => $v['title'],
                'price' => toNumber($v['price']),
                'price_level' => toNumber($v[$price_column]),
                'price_one' => toNumber($v['price_one']),
                'price_two' => toNumber($v['price_two']),
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 浏览记录
     * @param int $uid
     * @param int $gid
     * @param int $skuid
     */
    public function setRead($uid, $gid, $skuid)
    {
        $arys = [
            'uid' => $uid,
            'gid' => $gid,
            'sku_id' => $skuid,
            'addtime' => toDate(),
        ];
        $res = $this->dbwbConn($this->dbDistributorTrace)->insertGetId($arys);
        if (!$res) {
            return array('code' => -2, 'msg' => '该用户不存在');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 浏览记录
     * @param int $uid
     * @param array $days【start，end】
     */
    public function getTraceList($user, $days)
    {
        $price_column = $user['level'] == 1 ? 'price_one' : 'price_two';
        $uid = $user['id'];
        $res = $this->dbwbConn($this->dbDistributorTrace)
            ->where('uid', $uid)
            ->where('addtime', '>=', $days['start'])
            ->where('addtime', '<=', $days['end'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有历史数据', 'data' => []);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //商品信息
            $gOne = (array) $this->dbwbConn($this->dbDistributorGoods)
                //->distinct('gid')
                ->where('del', 0)
                ->where('id', $v['gid'])
                ->first();
            $gname = empty($gOne) ? '' : $gOne['title'];
            $gimg = empty($gOne) ? '' : $gOne['bigimg'];
            //SKU信息
            $skuDB = $this->dbwbConn($this->dbDistributorGsku)
                ->where('del', 0)
                ->where('gid', $v['gid']);
            if ($v['sku_id'] > 0) {
                $skuDB = $skuDB->where('id', $v['sku_id']);
            } else {
                $skuDB = $skuDB->orderBy('id', 'asc');
            }
            $skuOne = (array) $skuDB->first();
            $price = empty($skuOne) ? 0 : $skuOne[$price_column];
            $sku_name = empty($skuOne) ? '' : $skuOne['title'];
            //看看商品是否删除了
            $gOne = (array) $this->dbConn($this->dbDistributorGoods)
                ->where('del', 0)
                ->where('id', $v['gid'])
                ->first();
            $arys[] = [
                'id' => $v['id'],
                'gid' => $v['gid'],
                'sku_id' => $v['sku_id'],
                'gname' => $gname,
                'gimg' => env('DOMAIN') . '/' . $gimg,
                'price' => $price,
                'unit' => $sku_name,
                'cartNum' => $this->getCartTotal($uid, $v['id']),
                'gdel' => empty($gOne) ? 1 : 0,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }
}